<template>
  <BasicModal
    v-bind="$attrs"
    :defaultFullscreen="true"
    destroyOnClose
    :title="title"
    :width="800"
    :bodyStyle="{ background: '#f2fbff' }"
    @register="registerModal"
    @ok="handleSubmit"
  >
    <div class="form-container max-w-screen-lg">
      <a-form ref="formRef" :model="formModel" :rules="validatorRules" layout="vertical">
        <div class="box">
          <div class="hd">
            <h3 class="title">基本信息</h3>
          </div>
          <div class="bd">
            <a-row :gutter="12">
              <a-col :lg="24">
                <a-form-item label="景点名称" v-bind="validateInfos.attractionName">
                  <a-input v-model:value="formModel.attractionName" placeholder="请输入景点名称" :disabled="action=='view' || action=='auth'" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :sm="12" :md="8" :lg="6">
                <a-form-item label="景点分类" v-bind="validateInfos.attractionTheme">
                  <nTreeSelect v-model:value="formModel.attractionTheme" :is-root="false" :disabled="action=='view' || action=='auth'" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :sm="12" :md="8" :lg="6">
                <a-form-item label="建议游览时长(分钟)">
                  <a-input-number v-model:value="formModel.attractionRecommendedDuration" placeholder="请输入建议游览时长" :disabled="action=='view' || action=='auth'" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :sm="12" :md="8" :lg="6">
                <a-form-item label="最大承载量">
                  <a-input-number v-model:value="formModel.attractionCapacity" placeholder="请输入最大承载量" :disabled="action=='view' || action=='auth'" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :sm="12" :md="8" :lg="6">
                <a-form-item label="热门景点">
                  <JDictSelectTag v-model:value="formModel.isFeatured" placeholder="请选择" dict-code="yn" :disabled="action=='view' || action=='auth'" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :sm="12" :md="8" :lg="6">
                <a-form-item label="状态">
                  <JDictSelectTag v-model:value="formModel.attractionStatus" placeholder="请选择" dict-code="scenic_spot_status" :disabled="action=='view' || action=='auth'" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :sm="12" :md="8" :lg="6">
                <a-form-item label="营业时间">
                  <a-input v-model:value="formModel.businessHour" placeholder="请输入营业时间" :disabled="action=='view' || action=='auth'" />
                </a-form-item>
              </a-col>
              <a-col :lg="24">
                <a-form-item label="景点地址" v-bind="validateInfos.attractionAddress">
                  <addressSelect v-model:value="formModel.attractionAddress" placeholder="请选择地址" @success="addrSelectSuccess" :disabled="action=='view' || action=='auth'" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :sm="12" :md="8" :lg="6">
                <a-form-item label="联系人">
                  <a-input v-model:value="formModel.contactName" placeholder="请输入联系人姓名" :disabled="action=='view' || action=='auth'" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :sm="12" :md="8" :lg="6">
                <a-form-item label="联系电话" v-bind="validateInfos.contactPhone">
                  <a-input v-model:value="formModel.contactPhone" placeholder="请输入完整的手机号码" :disabled="action=='view' || action=='auth'" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :sm="12" :md="12" :lg="12">
                <a-form-item label="官网网址" v-bind="validateInfos.website">
                  <a-input v-model:value="formModel.website" placeholder="请输入完整的网址" :disabled="action=='view' || action=='auth'" />
                </a-form-item>
              </a-col>
            </a-row>
          </div>
        </div>
        <div class="box">
          <div class="hd">
            <h3 class="title">封面图片<span class="required">*</span></h3>
          </div>
          <div class="bd">
            <a-row :gutter="12">
              <a-col :lg="24">
                <a-form-item v-bind="validateInfos.imgFile">
                  <JImageUpload v-model:value="formModel.imgFile" :fileMax="9" :is-return-array="true" :disabled="action=='view' || action=='auth'" />
                </a-form-item>
              </a-col>
            </a-row>
          </div>
        </div>
        <div class="box">
          <div class="hd">
            <h3 class="title">音频文件</h3>
          </div>
          <div class="bd">
            <a-row :gutter="12">
              <a-col :lg="24">
                <a-form-item>
                  <JUpload v-model:value="formModel.mpFile" :maxCount="1" :is-return-array="true" accept=".mp3,.wav,.ogg" text="上传音频文件" :disabled="action=='view' || action=='auth'" />
                </a-form-item>
              </a-col>
            </a-row>
          </div>
        </div>
        <div class="box">
          <div class="hd">
            <h3 class="title">描述信息</h3>
          </div>
          <div class="bd">
            <a-row :gutter="12">
              <a-col :lg="24">
                <a-form-item>
                  <JEditor v-model:value="formModel.attractionDescription" :disabled="action=='view' || action=='auth'" />
                </a-form-item>
              </a-col>
            </a-row>
          </div>
        </div>
      </a-form>
    </div>
    <template #footer>
      <a-space v-if="action == 'add' || action == 'edit'">
        <a-button type="default" @click="closeModal">取消</a-button>
        <a-button type="primary" :loading="isLoading" :disabled="action!='add' && action!='edit'" @click="handleSubmit">
          {{ isLoading ? '提交中...' : '提交' }}</a-button>
      </a-space>
      <a-space v-if="action == 'auth'">
        <a-button type="error" :loading="isLoading" @click="handleAuthNoPass">
          审核不通过</a-button>
        <a-button type="primary" :loading="isLoading" @click="handleAuthPass">
          审核通过</a-button>
      </a-space>
    </template>
  </BasicModal>
  <reasonModal @register="registerReasonModal" @success="handleNoPassSubmit" />
</template>

<script lang="ts" setup>
  import { ref, reactive, computed, unref } from 'vue';
  import dayjs from 'dayjs';
  import { Form, Modal } from 'ant-design-vue';
  import { useDebounceFn } from '@vueuse/core';
  import { BasicModal, useModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { formSchema } from '../JhAttraction.data';
  import { saveOrUpdate, queryById, auth } from '../JhAttraction.api';
  import { isUrl, isTel, isEmptyExt } from '/@/utils/is';

  import addressSelect from '/@/components/Extend/addressSelect.vue';
  import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
  import JEditor from '/@/components/Form/src/jeecg/components/JEditor.vue';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import reasonModal from '/@/components/Extend/reasonModal.vue';

  //注册model
  const [registerReasonModal, { openModal: openReasonModal }] = useModal();
  // Emits声明
  const emit = defineEmits(['register','success']);
  const isUpdate = ref(true);
  const isDetail = ref(false);
  const formRef = ref();
  const action = ref('add');
  const isLoading = ref(false);
  // 是否为只读模式（详情查看时为只读）
  const isReadOnly = computed(() => !unref(isDetail));
  let formModel = reactive({
    attractionName: '',
    attractionTheme: '',
    attractionDescription: '',
    attractionRecommendedDuration: null,
    attractionCapacity: null,
    isFeatured: '0',
    attractionHeat: null,
    attractionStatus: '0',
    businessHour: null,
    attractionCountry: '中国',
    attractionProvince: '',
    attractionCity: '',
    attractionDistrict: '',
    areaCode: null,
    attractionAddress: '',
    longitude: 0,
    latitude: 0,
    contactName: '',
    contactPhone: '',
    website: '',
    photos: null,
    imgFile: [],
    mpFile: [],
    videoFile: [],
    // 其他字段...
  });
  const validatorRules = reactive({
    attractionName: [
      { required: true, message: '请输入景点名称' },
      { min: 2, max: 20, message: '景点名称长度在2到20个字符之间' },
    ],
    attractionTheme: [{ required: true, message: '请选择景点分类' }],
    attractionAddress: [{ required: true, message: '请输入景点地址' }],
    contactPhone: [
      {
        validator: (rule, value) => {
          if (!value) return Promise.resolve();
          if (!isTel(value)) {
            return Promise.reject('请输入正确的手机号码');
          }
          return Promise.resolve();
        },
      },
    ],
    website: [
      {
        validator: (rule, value) => {
          if (!value) return Promise.resolve();
          if (!isUrl(value)) {
            return Promise.reject('请输入正确的网址');
          }
          return Promise.resolve();
        },
      },
    ],
    imgFile: [{ required: true, message: '请上传至少一张图片' }],
    // 其他字段的验证规则...
  });
  //设置标题
  const title = computed(() => (!unref(isUpdate) ? '新增' : !unref(isDetail) ? '详情' : '编辑'));

  //表单配置
  const useForm = Form.useForm;
  const { resetFields, validate, validateInfos, clearValidate } = useForm(formModel, validatorRules, { immediate: false });

  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //重置表单
    await resetFields();
    setModalProps({ confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter });
    isUpdate.value = !!data?.isUpdate;
    isDetail.value = !data?.showFooter; // 修改这里，没有底部按钮时为详情模式
    action.value = isEmptyExt(data?.action) ? 'add' : data?.action;
    if (unref(isUpdate)) {
      console.log('赋值前！！', data.record.id);
      await fetchData(data.record.id);
      await clearValidate();
    }
  });

  async function fetchData(id) {
    let params = { id: id };
    let res = await queryById(params);
    console.log('fetchData', res);
    formModel = Object.assign(formModel, res);
    formModel.isFeatured = String(formModel.isFeatured);
    formModel.attractionStatus = String(formModel.attractionStatus);
    formModel.imgFile = isEmptyExt(formModel.imgFile) ? [] : formModel.imgFile.map(item => item.path);
    formModel.mpFile = isEmptyExt(formModel.mpFile) ? [] : formModel.mpFile.map(item => item.path);
  }

  const addrSelectSuccess = (data) => {
    console.log('addrSelectSuccess', data);
    formModel.attractionProvince = data.province;
    formModel.attractionCity = data.city;
    formModel.attractionDistrict = data.district;
    formModel.areaCode = data.adcode;
    formModel.attractionAddress = data.address;
    formModel.longitude = data.lng;
    formModel.latitude = data.lat;
  };

  const debouncedFn = useDebounceFn(async () => {
    formRef.value.validate().then(async () => {
      try {
        //let values = await validate();
        setModalProps({ confirmLoading: true });
        //提交表单
        if (!isEmptyExt(formModel.mpFile)) {
          formModel.mpFile = formModel.imgFile.indexOf(",") > -1 ? formModel.mpFile.split(",") : [formModel.mpFile];
        }else{
          formModel.mpFile = [];
        }
        await saveOrUpdate(formModel, isUpdate.value);
        //关闭弹窗
        closeModal();
        //刷新列表
        emit('success');
      } finally {
        setModalProps({ confirmLoading: false });
      }
    });
  }, 1000);
  //表单提交事件
  async function handleSubmit(v) {
    await validate();
    setModalProps({ confirmLoading: true });
    debouncedFn();
    // try {

    // } catch ({ errorFields }) {
    //   if (errorFields) {
    //     const firstField = errorFields[0];
    //     if (firstField) {
    //       scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
    //     }
    //   }
    //   return Promise.reject(errorFields);
    // } finally {
    //   setModalProps({ confirmLoading: false });
    // }
  }

  const debouncedFnAuth = useDebounceFn(async (params) => {
    try {
      isLoading.value = true;
      //提交表单
      await auth(params);

      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success');
    }finally {
      setModalProps({ confirmLoading: false });
      isLoading.value = false;
      formModel = {
        id: null,
        slideshowName: '',
        slideshowUrl: '',
        sortNo: 0,
      };
    }
  })
  async function handleNoPassSubmit(data){
    setModalProps({ confirmLoading: true });
    let params = {
      checkStatus: -1,
      id: formModel.id,
      checkRemark: data.reason,
    }
    console.log("params:",params)
    debouncedFnAuth(params);
  }
  // 审核不通过
  async function handleAuthNoPass() {
    openReasonModal(true, {
      showFooter: true,
    });
  }
  // 审核通过
  async function handleAuthPass() {
    setModalProps({ confirmLoading: true });
    let params = {
      id: formModel.id,
      checkStatus: 1,
    }
    debouncedFnAuth(params);
  }
</script>

<style lang="less" scoped>
  .form-container {
    padding: 24px;
    background: #fff;
    box-shadow: 0 0 4px rgba(0, 0, 0, .1);
    border-radius: 4px;
    margin: 0 auto;
    .box {
      .hd {
        .title {
          display: flex;
          justify-content: flex-start;
          align-items: center;
          font-size: 16px;
          font-weight: bold;

          &::before {
            content: '';
            display: block;
            width: 4px;
            height: 16px;
            background: @primary-color;
            margin: 0 6px 0 0;
            border-radius: 4px;
          }
        }
      }
    }
  }
  /** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.ant-calendar-picker) {
    width: 100%;
  }
  .required {
    color:@error-color; margin-left:4px;
  }
</style>
